/*
 * JHeuristics - The Java Meta-Heuritics Library
 * Copyright (C) 2004-2005, Universidade Federal de Campina Grande. All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package org.jheuristics.ga;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.epanetgrid.otimizacao.ag.InviaveisSelector;
import org.epanetgrid.otimizacao.ag.ViaveisSelector;
import org.epanetgrid.otimizacao.log.AGLogger;
import org.epanetgrid.otimizacao.simulation.GradienteNaoConvergeOtimizacaoException;
import org.epanetgrid.otimizacao.util.OtimizacaoUtil;
import org.jheuristics.Individual;
import org.jheuristics.ga.multiObjective.DistanceAlgorithm;
import org.jheuristics.ga.multiObjective.EuclidianDistanceAlgorithm;
import org.jheuristics.ga.operators.selectors.DefaultRepresentativosSelector;
import org.jheuristics.ga.operators.selectors.NonDominatedSelector;
import org.jheuristics.ga.operators.selectors.RepresentativosSelector;
import org.jheuristics.ga.transformations.DoubleFitnessToDoubleTransformation;
import org.jheuristics.ga.transformations.FitnessToDoubleTransformation;
import org.jheuristics.util.Condition;


/**
 * TODO
 *
 * @author Marcell Manfrin, marcell@ourgrid.org, Jan 9, 2006
 */
public class DefaultEvolver extends AbstractEvolver {
    private Operator initializeOperator;
	private String[] descricoes;
	private int representativas;

    /**
     * TODO
     *
     * @param initializeOperator
     * @param config
     */
    public DefaultEvolver(Operator initializeOperator, GAConfig config, String[] descricoes, int representativas) {
        super(config);
        this.initializeOperator = initializeOperator;
        this.descricoes = descricoes;
        this.representativas = representativas;
        setEvolutionStatus(createGAStatus(0, createEmptyPopulation(), createEmptyPopulation(), createEmptyPopulation(), createEmptyPopulation()));
    }

    /**
     * TODO
     *
     * @see org.jheuristics.ga.AbstractEvolver#initialize()
     */
    protected void initialize() throws GradienteNaoConvergeOtimizacaoException {
        if (null != initializeOperator) {
            initializeOperator.operate(getEvolutionStatus(), getGAConfiguration());
        }
        setEvolutionStatus(createGAStatus(getEvolutionStatus().getEvolutionAge() + 1, getEvolutionStatus().getSelectedIndividualsPopulation(), createEmptyPopulation(), createEmptyPopulation(), createEmptyPopulation()));
    }

    /**
     * TODO
     *
     * @see org.jheuristics.ga.Evolver#evolve()
     */
    public void evolve() throws GradienteNaoConvergeOtimizacaoException {
    	
        if (1 > getEvolutionStatus().getEvolutionAge()) {
            initialize();
        }
        
        logGeracao();
        getGAConfiguration().getOperator().operate(getEvolutionStatus(), getGAConfiguration());
        setEvolutionStatus(createGAStatus(getEvolutionStatus().getEvolutionAge() + 1, getEvolutionStatus().getSelectedIndividualsPopulation(), createEmptyPopulation(), createEmptyPopulation(), createEmptyPopulation()));
    }

    /**
     * TODO
     *
     * @param contition
     * @see org.jheuristics.ga.Evolver#evolve(org.jheuristics.util.Condition)
     */
    public void evolve(Condition contition) throws GradienteNaoConvergeOtimizacaoException {
        if (1 > getEvolutionStatus().getEvolutionAge()) {
            initialize();
        }
        while (contition.check(new Object[] {getEvolutionStatus(), getGAConfiguration()})) {
            evolve();
        }
        logGeracao();
    }
    
    private void logGeracao() {
    	GAStatus status = getEvolutionStatus();
    	StringBuffer buffer = new StringBuffer();
    	buffer.append("\n*******************\n");
    	buffer.append("GERAÇÂO: ");
    	buffer.append(status.getEvolutionAge());
    	buffer.append("\n*******************\n");
    	AGLogger.getInstance().debug(buffer);
    	buffer = new StringBuffer();
    	
    	buffer.append("\nLegenda: ");
    	buffer.append(Arrays.toString(descricoes));
    	buffer.append("\n");
    	
    	buffer.append("População: \n");
    	buffer.append(OtimizacaoUtil.format(status.getCurrentPopulation()));
    	
    	//-3 tirando ponto de falha, severidade e tipoDeMutacao, testa se eh multi
    	if(AGLogger.getInstance().isSelected(AGLogger.DEBUG) && (descricoes.length-3 > 1)) {
        	
        	Population viaveis =  new DefaultPopulation();
    		viaveis.addIndividuals(new ViaveisSelector().select(status.getCurrentPopulation(), 0, null, null));
    		buffer.append("Número de Cromossomos viáveis: ");
    		buffer.append(viaveis.size());
    		buffer.append("\n");
    		
    		Population inviaveis =  new DefaultPopulation();
    		inviaveis.addIndividuals(new InviaveisSelector().select(status.getCurrentPopulation(), 0, null, null));
    		buffer.append("Número de Cromossomos inviáveis: ");
    		buffer.append(inviaveis.size());
    		buffer.append("\n");	
    		
    		Population viaveisNaoDominados =  new DefaultPopulation();
    		viaveisNaoDominados.addIndividuals(new NonDominatedSelector().select(viaveis, 0, null, null));
    		buffer.append("Número de Cromossomos não dominados viáveis: ");
    		buffer.append(viaveisNaoDominados.size());
    		buffer.append("\n");	
    		
    		Population inviaveisNaoDominados =  new DefaultPopulation();
    		inviaveisNaoDominados.addIndividuals(new NonDominatedSelector().select(inviaveis, 0, null, null));
    		buffer.append("Número de Cromossomos não dominados inviáveis: ");
    		buffer.append(inviaveisNaoDominados.size());
    		buffer.append("\n");
    		
    		if(descricoes.length > 3) {
    			//-3 tirando ponto de falha, severidade e tipoDeMutacao
    			FitnessToDoubleTransformation[] transformations = new DoubleFitnessToDoubleTransformation[descricoes.length - 3];
    			for (int i = 0; i < transformations.length; i++) {
    				transformations[i] = new DoubleFitnessToDoubleTransformation();
    			}
    			//encontrando os minimos viaveis nao dominados
    			List minimosViaveis = new LinkedList();
    			
    			buffer.append("Mínimos viáveis não dominados:");
    			buffer.append("\n");
    			
    			for (Object individual : minimosViaveis) {
    				buffer.append(individual);
    				buffer.append("\n");
    			}
    			
    			Individual[] representativos = new RepresentativosSelector(new DefaultRepresentativosSelector(transformations.length)).select(status.getCurrentPopulation(), representativas, null, null);
    			
    			buffer.append("Indivíduos Representativos:");
    			buffer.append("\n");
    			
    			for (int i = 0; i < representativos.length; i++) {
    				buffer.append(representativos[i]);
    				buffer.append("\n");
    			}
    			
    			DistanceAlgorithm distanceAlgorithm = new EuclidianDistanceAlgorithm(transformations);
    			
    			Population currentPop = status.getCurrentPopulation();
    			
    			if(currentPop.size() > 1) {
    				
    				List[] distancias = distanceAlgorithm.getDistances(currentPop.toIndividualArray(), getEvolutionStatus(), getGAConfiguration());
    				
    				buffer.append("\nDistâncias: ");
    				for (List distancia : distancias) {
    					buffer.append(Arrays.toString(distancia.toArray(new Double[0])));
    					buffer.append("\n");
    				}
    			}
    			
    		}
    	}
    	AGLogger.getInstance().debug(buffer);
    }

	public String[] getDescricoes() {
		return descricoes;
	}

	public int getRepresentativas() {
		return representativas;
	}
    
}
